package gupao.concurrency.kms.disruptor;

import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.WorkHandler;
import gupao.concurrency.kms.RequestModel;
import gupao.concurrency.kms.SimpleRequestValidator;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class DefaultOrderEventHandler implements
        EventHandler<OrderEvent>, WorkHandler<OrderEvent> {
    public static volatile int total = 0;
    public static AtomicInteger totalSucc = new AtomicInteger(0);
    public static AtomicInteger totalFail = new AtomicInteger(0);
    SimpleRequestValidator validator = new SimpleRequestValidator();

    @Override
    public void onEvent(OrderEvent event, long sequence, boolean endOfBatch) {
        doEvent(event);
    }
    @Override
    public void onEvent(OrderEvent event) {
        doEvent(event);
    }
    private void doEvent(OrderEvent event){
        RequestModel req = (RequestModel) event.getData();
        if(req != null){
            if (validator.validateRequest(req, "rf")) {
                if(totalSucc.incrementAndGet() == total){
                    log.info("[Completed]");
                    ResultCollector.onCompleted();
                }
            } else {
                totalFail.incrementAndGet();
            }
        }
    }
}
